/*
 *    Copyright © OpenAtom Foundation.
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */

package com.inspur.edp.bff.spi.response;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.MapperFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.inspur.edp.bff.api.exception.BffFrameworkException;
import com.inspur.edp.bff.api.extend.IBffEntityExtend;
import com.inspur.edp.bff.api.manager.IFSManager;
import com.inspur.edp.bff.spi.AbstractBffEntitySerConvertor;
import com.inspur.edp.bff.spi.changeset.AbstractBffChangeJsonSerializer;
import com.inspur.edp.bff.spi.utils.VoJsonSerializer;
import com.inspur.edp.cef.api.manager.serialize.CefSerializeContext;
import com.inspur.edp.cef.api.manager.serialize.JsonFormatType;
import com.inspur.edp.cef.api.message.IBizMessage;
import com.inspur.edp.cef.api.response.ResponseInfo;
import com.inspur.edp.cef.entity.changeset.IChangeDetail;
import com.inspur.edp.cef.entity.entity.IEntityData;
import com.inspur.edp.cef.entity.entity.IEntityDataCollection;
import com.inspur.edp.cef.spi.entity.resourceInfo.builinImpls.CefEntityResInfoImpl;
import com.inspur.edp.cef.variable.api.manager.IVariableManager;
import com.inspur.edp.commonmodel.spi.AbstractEntityDataSerializer;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;

public abstract class ResponseConvertor extends VoJsonSerializer<ResponseInfo> {

    private static final String TitleResult = "returnValue";
    private static final String TitleInnerChange = "innerDataChange";
    private static final String TitleMessage = "message";
    private static final String TitleVarChange = "innerVariableChange";
    private static final String TitleViewRule = "viewRule";

    private CefSerializeContext context;
    private IFSManager fsManager;
    private List<IBffEntityExtend> extList;

    protected abstract IFSManager createFsManager();

    protected abstract AbstractBffChangeJsonSerializer getJsonConverter();

    @Override
    public void serialize(ResponseInfo response, JsonGenerator jsonGenerator, SerializerProvider serializerProvider)
            throws IOException {

        if (response == null) {
            return;
        }

        fsManager = createFsManager();
        jsonGenerator.writeStartObject();//writer.WriteStartObject();
        //①ReturnValue
        jsonGenerator.writeFieldName(TitleResult); //writer.WritePropertyName(TitleResult);
        writeResult(jsonGenerator, response.getReturnValue(), serializerProvider);
//        serializer.Serialize(writer, response.getReturnValue());
        //②InnerChange
        //writer.WritePropertyName(TitleInnerChange);
        jsonGenerator.writeFieldName(TitleInnerChange);
        writeInnerChanges(jsonGenerator, response.getInnerDataChange(), serializerProvider);
        //③Message
        jsonGenerator.writeFieldName(TitleMessage);// writer.WritePropertyName(TitleMessage);
        writeMessage(jsonGenerator, response.getMessage(), serializerProvider);

        //④InnerVariableChange
        jsonGenerator.writeFieldName(TitleVarChange);
        writeInnerVarChange(jsonGenerator, response.getInnerVariableChange(), serializerProvider);

        //5、界面规则，不支持平铺格式
        if (context == null || context.getJsonFormatType() != JsonFormatType.Tiled) {
            jsonGenerator.writeFieldName(TitleViewRule);
            String viewRuleJson = getDefaultJsonMapper().writeValueAsString(response.getViewRule());
            jsonGenerator.writeRawValue(viewRuleJson);
        }

        jsonGenerator.writeEndObject();// writer.WriteEndObject();
    }

    private void writeResult(JsonGenerator writer, Object result, SerializerProvider serializer) throws IOException {

        AbstractBffEntitySerConvertor dataConverter = getDataJsonConverter();

        if (dataConverter == null || context == null || context.getJsonFormatType() != JsonFormatType.Tiled) {
            writer.writeObject(result);
            return;
        }
        IEntityData data = fsManager.createData();
        Class dataClass = data.getClass().getInterfaces()[0];
        ObjectMapper mapper = getDefaultJsonMapper();
        SimpleModule module = new SimpleModule();
        if (extList != null) {
            extList.forEach(item -> dataConverter.addExtend(item));
        }
        dataConverter.setCefSerializeContext(context);
        module.addSerializer(dataClass, dataConverter);
        IBffEntityExtend rootEntityExtend = getRootEtityExtend(extList);
        addChildConverter(data, module, dataConverter, rootEntityExtend);
        mapper.configure(MapperFeature.USE_ANNOTATIONS, false);
        mapper.registerModule(module);
        String value = mapper.writeValueAsString(result);
        writer.writeRawValue(value);
    }

    private void addChildConverter(IEntityData currentData, SimpleModule module, AbstractEntityDataSerializer dataConverter, IBffEntityExtend parentEntityExtend) {
        HashMap<String, IEntityDataCollection> childs = currentData.getChilds();
        if (childs == null || childs.size() < 1)
            return;
        for (String nodeCode : childs.keySet()) {
            IEntityData childData = (IEntityData) currentData.createChild(nodeCode);
            Class dataClass = childData.getClass().getInterfaces()[0];
            AbstractEntityDataSerializer childConvertor = dataConverter.getChildDataConvertor(nodeCode);
            IBffEntityExtend childEtityExtend = getChildEtityExtend(parentEntityExtend, nodeCode);
            if (childEtityExtend != null) {
                childConvertor.addExtend(childEtityExtend);
            }
            childConvertor.setCefSerializeContext(context);
            module.addSerializer(dataClass, childConvertor);
            addChildConverter(childData, module, childConvertor, childEtityExtend);
        }
    }

    private IBffEntityExtend getRootEtityExtend(List<IBffEntityExtend> extendList) {
        if (extendList == null)
            return null;
        IBffEntityExtend extend = null;
        for (IBffEntityExtend rootEntityExtend : extendList) {
            extend = rootEntityExtend;
        }
        return extend;
    }

    private IBffEntityExtend getChildEtityExtend(IBffEntityExtend extend, String nodeCode) {
        if (extend == null)
            return null;
        return extend.getChildEntity(nodeCode);
    }

    private void writeInnerVarChange(JsonGenerator writer, IChangeDetail innerVariableChange, SerializerProvider serializer) {

        if (innerVariableChange != null) {
            IVariableManager varManager = fsManager.createVariableManager();
            try {
                writer.writeRawValue(varManager.serializeChange(innerVariableChange));
            } catch (IOException e) {
                throw new BffFrameworkException(e);
            }
        } else {
            try {
                writer.writeNull();
            } catch (IOException e) {
                throw new BffFrameworkException(e);
            }
        }
    }

    private void writeInnerChanges(JsonGenerator writer, java.util.HashMap<String, IChangeDetail> innerChange, SerializerProvider serializer) throws IOException {
        writer.writeStartArray();
        if (innerChange == null || innerChange.size() < 1) {
            writer.writeEndArray();
            return;
        }

        for (IChangeDetail changeDetail : innerChange.values()) {
            writeInnerChanges(writer, changeDetail, serializer);
        }

        writer.writeEndArray();
    }

    private void writeInnerChanges(JsonGenerator writer, IChangeDetail innerChange, SerializerProvider serializer) throws IOException {
        AbstractBffChangeJsonSerializer converter = getJsonConverter();
        converter.setCefSerializeContext(context);
        converter.writeJson(innerChange, writer, serializer);
    }

    private void writeMessage(JsonGenerator writer, java.util.List<IBizMessage> message, SerializerProvider serializer) throws IOException {
        if (message == null || message.size() < 1) {
            writer.writeStartArray();
            writer.writeEndArray();
            return;
        }

        String messageStr = getDefaultJsonMapper().writeValueAsString(message);
        writer.writeRawValue(messageStr); //WriteRawValue(messageStr);
    }

    private ObjectMapper getDefaultJsonMapper() {
        ObjectMapper mapper = new ObjectMapper();
        SimpleModule module = new SimpleModule();
        mapper.registerModule(module);
        return mapper;
    }

    public void setExtList(List<IBffEntityExtend> extList) {
        this.extList = extList;
    }

    public void setContext(CefSerializeContext context) {
        this.context = context;
    }

    protected AbstractBffEntitySerConvertor getDataJsonConverter() {
        return null;
    }

    /**
     * 表单运行时调用
     *
     * @param nodeCode 节点编号
     * @return CefResourceInfo
     */
    protected CefEntityResInfoImpl cefEntityResInfo(String nodeCode) {
        return (CefEntityResInfoImpl) createFsManager().getModelInfo().getCustomResource(nodeCode);
    }
}
